<?php

/**
 * Register is a page that allows a user to register a student for a course
 * and handles the billing of tuition as well as special fees for each course
 * @Author Ryan Olson
 * @version 1.0
 */

@session_start();
require_once 'shared-functions.php';
require_once 'session.php';
require_once 'masterpage.php';

//Make sure the student is logged in
if (!IsValidSession()) {
    header('Location: login.php?page=register');
    exit();
}
else
{
    RefreshSession();
}


$user = GetCurrentUserAccessLevel();

//Check user access
if ($user != $DIRECTOR && $user != $ADMIN && $user != $REGISTRAR) {
    header('Location: login.php?page=register&error=To access to the registration page, please log in as a director, admin or registrar&logout=1');
    exit();
}

//You need a student to perform registration for, if not chosen, redirect to student selector
//if (!isset($_POST['StudentID']))
//{
//    header('Location: student-selector.php?page=register');
//}

masterpage("Registration");

if(isset($_POST['ProgramID']))
{
	///if semester and program are chosen, we can register students
	if(isset($_POST['SemesterID']))
	{
			//Get the student's in the program to register
			$link = connect_db();
			//query to get students in the program
			$query = "SELECT * FROM `Student` WHERE `programID` = '".$_POST['ProgramID']."'";
			$students = mysql_query($query, $link);
			
			if (!$students) {
				echo "Oops...something went wrong. Please contact support.";
				echo " (while getting students in the program) "; 
				echo " <br /> Query: ".$query;
				exit();
			}
			
			$studentCount = mysql_num_rows($students);
			
			//query to get all the course instances in the chosen semester
			$query = "SELECT * FROM `CourseInstance` WHERE `semesterID` = '".$_POST['SemesterID']."'";
			$courses = mysql_query($query, $link);
			
			if(!$courses)
			{
				echo "Oops...something went wrong. Please contact support.";
				echo " (while getting courses in a semester) "; 
				exit();
			}
				
			$registeredStudentsCount = 0;	
			//Loop through students to register each for the semesters classes	
			while($student = mysql_fetch_array($students, MYSQL_BOTH))
			{				
				//Check if the student is registered for any classes in this semester
				$query = "SELECT * FROM `CourseEnrollment`
							INNER JOIN `CourseInstance` ON `CourseInstance`.`InstanceID` = `CourseEnrollment`.`CourseInstanceID`
							WHERE `CourseInstance`.`semesterID` = '".$_POST['SemesterID']."'
							AND `StudentID` = '".$student['ID']."'";
				$courses = mysql_query($query, $link);
				
				$query = "SELECT * FROM `CourseInstance`
							WHERE `CourseInstance`.`semesterID` = '".$_POST['SemesterID']."'
							AND `StudentID` = '".$student['ID']."'";
				$semesterClasses = mysql_query($query, $link);

				//If the student hasn't registered for any courses this semester
				if(mysql_num_rows($courses) == 0)
				{
					//query to get the program the student is in (to get the tuition to charge)
					$query = "SELECT `TuitionFee` FROM `Student`
								INNER JOIN `Program` ON `Student`.`programID` = `Program`.`ProgramID`
								WHERE `Student`.`ID` = '".$student['ID']."'";
					$programs = mysql_query($query, $link);
					$program = mysql_fetch_row($programs);
					$tuition = $program[0];
					//query to insert a charge for tuition
					$query = "INSERT INTO `FeeLedger` (`StudentID`,
								  `Date`,
								  `Type`,
								  `Amount`,
								  `ProcessingUser`)
								  VALUES
								  ('" . $student['ID'] . "',
								   '" . date('Y-m-d H:i:s') . "',
								   '3',
								   '" . $tuition . "',
								   '" . GetSessionUser() . "');";
					$results = mysql_query($query, $link);
					if(!$results)
					{
						echo 'Oops something went wrong.. please contact support';
						exit();
					}
					else
					{
						addLogEntry('FeeLedger', 'Tuition charged for student '.$student['ID']);
					}
				}
				//Query to get the courses in the semester that the student isn't registered for
				$query = "SELECT * FROM `CourseInstance` WHERE `semesterID` = '".$_POST['SemesterID']."'
							AND `CourseInstance`.`InstanceID` NOT IN 
										(
										Select `CourseInstance`.`InstanceID`
										FROM `CourseInstance` 
										INNER JOIN `CourseEnrollment` 
											ON `CourseInstance`.`InstanceID` = `CourseEnrollment`.`CourseInstanceID`
										WHERE `StudentID` = '".$student['ID']."'
										)";
				$courses = mysql_query($query, $link);
				
				if(!$courses)
				{
					echo 'Oops something went wrong.. please contact support.';
					echo mysql_error();
					exit;	
				}
				if(mysql_num_rows($courses) > 0)
				{
					$registeredStudentsCount++;	
				}
				//Loop through classes and try to register the student for each
				while($course = mysql_fetch_array($courses, MYSQL_BOTH))
				{
					//registration logic
					//query to handle the enrollment of the course for the student
					$query = "INSERT INTO `CourseEnrollment` 
								(`CourseInstanceID`, `StudentID`) 
								VALUES 
								('".$course['InstanceID']."', '".$student['ID']."')";
					$insertEnrollment = mysql_query($query, $link);
					
					if(!$insertEnrollment)
					{
						echo 'Oops something went wrong.. please contact support.';
						echo mysql_error();
						exit;	
					}
					
					//Get the courses special fee for the course the student is being registered for
					$query = "SELECT * FROM `CourseInstance`
								INNER JOIN `Course` ON `Course`.`CourseID` = `CourseInstance`.`CourseID`
								WHERE `CourseInstance`.`InstanceID` = '".$course['InstanceID']."'";
	
					$specialFees = mysql_query($query, $link);
					$specialFee = mysql_fetch_array($specialFees, MYSQL_ASSOC);
					
					//Add special fee for course to student's fee ledger
					$query = "INSERT INTO `FeeLedger` (`StudentID`,
									  `Date`,
									  `Type`,
									  `Amount`,
									  `ProcessingUser`)
									  VALUES
									  ('" . $student['ID'] . "',
									   '" . date('Y-m-d H:i:s') . "',
									   '33',
									   '" . $specialFee['SpecialFee'] . "',
									   '" . GetSessionUser() . "');";
	
					$results = mysql_query($query, $link);
					if(!$results)
					{
						echo 'Oops.. something went wrong. Please contact support.';
						exit();
					}
					else
					{
						addLogEntry('FeeLedger', 'Registered student '.$student['ID'].' for '.$specialFee['Name'].'');
					}
				}
			}
		echo '<h3>Registration Successful</h3>';
		echo '<Br />';
		echo '<small><b>Details:</b><Br />';
		echo 'Students in program: '.$studentCount.'<br />';
		echo 'Students newly registered: '.$registeredStudentsCount.'<br /></small>';
	}
	else //choose semester to register for
	{
	
		//Get available semesters (for registration)
	
		$now = date('d-m-Y');
	
		//earliest available registration date
		$beginRange = date('d-m-Y');
	
		//latest available registration date
		$endRange = date('d-m-Y', strtotime('+1 week'));
	
		//create query to look for available semesters for registration
		//----UNCOMMENT IF YOU WANT REGISTRATION TO HAVE A START DATE AND END DATE------------------------------------------//
		//$query = "Select * FROM `Semester` WHERE `StartDate` > '".$beginRange."' AND `StartDate` < '".$endRange."'";
		$query = "Select * FROM `Semester`";
		//TODO add filter by program to query
		//$query = "Select * FROM `Semester` WHERE `programID` = '".$_POST['ProgramID']."'";
		$link = connect_db();
		$results = mysql_query($query, $link);
		if(!$results)
		{
			echo 'Oops something went wrong. please contact support.';
		}
		if(mysql_num_rows($results) > 0)
		{
			echo 'Semester: <br />';
			echo '<form action="register.php" method="post">';
			echo '<select name="SemesterID">';
			while($semester = mysql_fetch_array($results, MYSQL_BOTH))
			{
				echo '<option value="'.$semester[semesterID].'">'.$semester[Description].'</option>';
			}
			echo '</select>';
			echo '<input type="hidden" name="ProgramID" value="'.$_POST['ProgramID'].'" />';
			echo '<input type="submit" value="Register" />';
			echo '</form>';
		}
		else
		{
			echo 'No semesters found to register for';
		}
	}
}
else
{
	$link = connect_db();
	$query = "SELECT `ProgramID`,`Name`,`Code`,`Year`,`Semester` FROM `Program`;";
	$result = mysql_query($query,$link);
	if(!$result)
	{
		echo 'Oops something went wrong.. please contact support.';
		exit;	
	}
	
	if(mysql_num_rows($result) > 0)
	{
		echo '<small>Please select the program you want to register</small><br /><br />';
		echo 'Program: <br />';
		echo '<form action="register.php" method="post">';
		echo '<select name="ProgramID">';
		while($program=mysql_fetch_array($result,MYSQL_BOTH))
		{
			echo '<option value ="'.$program['ProgramID'].'">'.$program['Name'].', '.
															   $program['Code'].'-'.
															   str_pad($program['Semester'], 2, '0', STR_PAD_LEFT).'-'.
															   $program['Year'].'</option>';
		}
		echo '</select>';
		echo '<input type="submit" value="Select" />';
		echo '</form>';
	}
	else
	{
		echo 'No programs to register.  To add a new program <a href="add-new-program">click here</a>';	
	}
}

endmasterpage();

?>